from fastapi import APIRouter, Depends, File, Form, UploadFile, HTTPException
from sqlalchemy.orm import Session
import os
import uuid
from typing import List, Optional
import datetime

from ..database import get_db
from ..models import File as FileModel, User
from ..schemas import File as FileSchema,FileUpdate
from ..auth import get_current_active_user

router = APIRouter(prefix="/api/chance/files", tags=["files"])

# 本地存储路径
LOCAL_STORAGE_PATH = "/home/iscxiao/columba/static_resources/chance_uploads"

# 确保存储目录存在
def ensure_directory_exists(path):
    if not os.path.exists(path):
        os.makedirs(path)

# 获取文件扩展名
def get_file_extension(filename):
    if "." in filename:
        return filename.rsplit(".", 1)[1].lower()
    return ""

# 获取文件类型
def get_file_type(filename):
    extension = get_file_extension(filename)
    image_extensions = ["jpg", "jpeg", "png", "gif", "bmp", "tiff", "svg"]
    document_extensions = ["doc", "docx", "pdf", "txt", "md", "rtf", "odt"]
    spreadsheet_extensions = ["xls", "xlsx", "csv", "ods"]
    presentation_extensions = ["ppt", "pptx", "odp"]
    archive_extensions = ["zip", "rar", "tar", "gz", "7z"]
    audio_extensions = ["mp3", "wav", "ogg", "flac", "aac"]
    video_extensions = ["mp4", "avi", "mov", "mkv", "wmv"]
    
    if extension in image_extensions:
        return "图片"
    elif extension in document_extensions:
        return "文档"
    elif extension in spreadsheet_extensions:
        return "表格"
    elif extension in presentation_extensions:
        return "演示文稿"
    elif extension in archive_extensions:
        return "压缩包"
    elif extension in audio_extensions:
        return "音频"
    elif extension in video_extensions:
        return "视频"
    else:
        return "其他"

# 保存文件到本地
def save_file_to_local(file: UploadFile, file_id: str) -> str:
    # 确保存储目录存在
    ensure_directory_exists(LOCAL_STORAGE_PATH)
    
    # 生成唯一文件名
    file_extension = get_file_extension(file.filename)
    unique_filename = f"{file_id}.{file_extension}" if file_extension else file_id
    
    # 完整文件路径
    file_path = os.path.join(LOCAL_STORAGE_PATH, unique_filename)
    
    # 保存文件
    try:
        with open(file_path, "wb") as buffer:
            content = file.file.read()
            buffer.write(content)
        return unique_filename
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"文件保存失败: {str(e)}")

# 获取文件大小
def get_file_size(file_path: str) -> int:
    return os.path.getsize(file_path)

# 获取所有文件
@router.get("/", response_model=List[FileSchema])
async def get_files(
    skip: int = 0,
    limit: int = 10,
    filename: Optional[str] = None,
    db: Session = Depends(get_db)
):
    query = db.query(FileModel)
    
    if filename:
        query = query.filter(FileModel.filename.contains(filename))
        query = query.filter(FileModel.display_name.contains(filename))
    
    files = query.offset(skip).limit(limit).all()
    return files

# 上传文件
@router.post("/", response_model=FileSchema)
async def upload_file(
    file: UploadFile = File(),
    display_name: str = Form(None),
    description: str = Form(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):  
    # 验证文件
    if not file:
        raise HTTPException(status_code=500, detail="文件是必需的")
    
    # 生成文件ID
    file_id = str(uuid.uuid4())
    
    # 保存文件到本地
    saved_filename = save_file_to_local(file, file_id)
    
    # 计算文件大小
    file_path = os.path.join(LOCAL_STORAGE_PATH, saved_filename)
    file_size = get_file_size(file_path)
    
    # 确定文件类型
    file_type = get_file_type(file.filename)
    
    # 创建文件记录
    file_data = FileModel(
        uuid=file_id,
        saved_filename=saved_filename,
        filename=file.filename,
        display_name=display_name or file.filename,
        description=description,
        file_size=file_size,
        file_type=file_type,
        file_path=file_path,
        watch_num=0,
        uploader_id=current_user.id,
        created_at=datetime.datetime.now(),
        updated_at=datetime.datetime.now()
    )
    
    db.add(file_data)
    db.commit()
    db.refresh(file_data)
    return file_data

# 获取单个文件
@router.get("/{file_id}", response_model=FileSchema)
async def get_file(
    file_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    file = db.query(FileModel).filter(FileModel.id == file_id).first()
    if not file:
        raise HTTPException(status_code=404, detail="文件不存在")
    return file

# 更新文件信息
@router.put("/{file_id}", response_model=FileSchema)
async def update_file(
    file_id: str,
    file_update: FileUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    file = db.query(FileModel).filter(FileModel.id == file_id).first()
    if not file:
        raise HTTPException(status_code=404, detail="文件不存在")
    
    update_data = file_update.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(file, key, value)

    file.updated_at = datetime.datetime.now()
    
    db.commit()
    db.refresh(file)
    
    return file